// ignore_for_file: prefer_const_literals_to_create_immutables, use_build_context_synchronously

import 'dart:async';
 
import 'dart:math';
import 'dart:ui';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:junyeyishu/ui/home/widgets/QGLimitWidget.dart';
import 'package:junyeyishu/ui/home/widgets/QGOpenWalletWidget.dart';
import 'package:junyeyishu/ui/mine/widget/QGSendCodeWidget.dart';
import 'package:junyeyishu/ui/mine/widget/QGSendCodeWidget1.dart';
import 'package:junyeyishu/ui/sale/widgets/QGBatchAlert.dart';
import 'package:junyeyishu/ui/sale/widgets/QGSortWidget.dart';
import 'package:junyeyishu/ui/sale/widgets/QGSaleDetailCell.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGButton.dart';
import 'package:junyeyishu/widgets/QGListState.dart';
import 'package:junyeyishu/widgets/QGNavigationBar.dart';

import 'widgets/QGSaleRecordCell.dart';

class QGSaleDetailPage extends StatefulWidget {
  String id;
  QGSaleDetailPage({super.key, required this.id});
  @override
  State<QGSaleDetailPage> createState() => _QGSaleDetailPageState();
}

class _QGSaleDetailPageState extends QGListState<QGSaleDetailPage> {
  bool isWallet = false;
  bool isBatch = false;
  bool isPurchase = false;

  int ttype = 0;

  Timer? timer;

  int type = 0;
  dynamic headData;

  StreamSubscription? subs;
  bool unlock = true;

  @override
  void dispose() {
    timer?.cancel();
    subs?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    listURL = url_market_collectionList;
    listKey = "data";
    onRefresh();

    subs = eventBus.on<EventRefreshPurshase>().listen((obj) {
      if(ttype==2){
        listURL = url_ask_orderList;
      }else if(ttype==1){
        listURL = url_entrust_orderList;
      }
      
      listKey = "list";
      onRefresh();
    });

    setupHeadData();
  }

  @override
  onRefresh() {
    super.onRefresh();

    if (User.isLogin) {
      Network.post(url_u_getMergedUserInfo).then((res) {
        if (!res.success) {
          return;
        }
        isWallet = res.data["huifu_wallet"] == 1;
        isBatch = res.data["batch_buy"] == 1;
      });
    }
  }

  setupHeadData() {
    Network.post(url_goods_goodsInfo, data: {"pid": widget.id}).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      headData = res.data;
      if (res.data["ask_price_limit"] is String) {
        isPurchase = true;
      }

      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  listParam() {
    Map param = {"pid": widget.id};
    if (type == 0) {
      param["priceSort"] = "asc";
    } else if (type == 1) {
      param["noSort"] = "asc";
    }
    return param;
  }

  @override
  canUpdateList(data) {
    return true;
  }

  var allnums;

  @override
  onResponse(res) {
    allnums = res.ret["allnums"];
  }
  
   bool animSwitch = true;
  bool onNotification(note) {
    final offset = note.metrics.pixels.toInt();
    if (offset < -10 && animSwitch) {
      animSwitch = false;
      setState(() {});
    } else if (offset > -10 && !animSwitch) {
      animSwitch = true;
      setState(() {});
    }
    return false;
  }

  onLoad1() {
    if (listURL == null) return;

    final param = listParam();
    param["page"] = ++page;
     
        Map<String, dynamic> stringMap = param.cast<String, dynamic>();

    Network.post(listURL, data: stringMap).then((res) {
      if (!res.success) {
        toast(res.msg);
        page -= 1;
        refreshController.finishLoad(IndicatorResult.fail);
        return;
      }

      if (res.data is String) {
        res.data = decryptToJson(res.data);
      }

      res.data = resetData(res.data);

      var temp = [];

      if (res.data is List) {
        temp = res.data ?? [];
      } else if (res.data is Map) {
        temp = res.data[listKey] ?? [];
      }
      var allnums = 0;

      if (res.data is List) {
        allnums = int.parse("${res.ret?["allnums"] ?? "0"}");
      } else if (res.data is Map) {
        allnums = int.parse("${res.data?["allnums"] ?? "0"}");
      }

      list.addAll(temp);

      if (list.length >= allnums) {
        refreshController.finishLoad(IndicatorResult.noMore);
      } else {
        refreshController.finishLoad();
      }

      onUpdateList(list);
      if (mounted) setState(() {});
    });
  }
  

  @override
  Widget build(BuildContext context) {
    return 
    Scaffold(
        backgroundColor: const Color(0xFF232A32),

        body:

        Stack(children: [

        EasyRefresh(
          controller: refreshController,
          onRefresh: onRefresh,
          onLoad:onLoad1,
          child: NotificationListener(
            onNotification: onNotification,
            child: 
            //  Stack(children: [
            SingleChildScrollView(
              child:
                Column(
              children: [
                buildHeader(),
                SizedBox(height: 10.rpx),
                buildSort(),
                SizedBox(height: 15.rpx),
                list!=null && list.isNotEmpty?
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 15.rpx),
                   decoration: BoxDecoration(
                      color:Color(0XFF0C1012),
                        borderRadius: BorderRadius.circular(10.rpx)
                      ),
                  child: Column(
                    children: [
                      if(list!=null && list.isNotEmpty)
                for(var item in list)

            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){

              //  if (ttype == 2) {
              //     item["thumb_img"] = headData?["thumb_img"];
              //     item["total"] = headData?["total"];
              //     child: QGSaleRecordCell(data: item ?? {});
              //   }

                if(ttype==2||ttype==1){
                    bool isSaled = item["own_num"] > 0;
                  if (!isSaled) {
                        toast("您没有此藏品");
                        return;
                      }

                      item["name"] = item["order_name"];
                      item["order_price"] = item["total_fee"];
                      item["thumb_img"] = headData["thumb_img"];
                      item["ttype"] = ttype;
                      Navigator.of(context).pushNamed(PagePurchaseConfirm, arguments: item);
                      return;
                }

                  //寄售
                 if (item["isOwner"] == 1) {
                  toast("不能购买自己流转的藏品");
                  return;
                }
          
                Navigator.of(context).pushNamed(
                  inReview() ? PageReviewTradeDetail : PageTradeNFTDetail,
                  arguments: item["cid"]);

              },
              child: QGSaleDetailCell(data: item ?? {},ttype:ttype),
            )
                


                    ],

                  )
                  
                ,
                ):SizedBox(height: 500.rpx,)
               ,
               
                inReview()
                    ? Container(height: max(10, kSafeBottom))
                    : SizedBox(height: 54.rpx + max(10, kSafeBottom)),
          ],
        )
              ),
             

              // ])

              
              ))

          
        // Stack(
        //   children: [
        //     Column(
        //       children: [
        //         // ListView(
        //         //  children: [
                  
        //         //  ],
        //         // )
        //         buildHeader(),
        //         SizedBox(height: 10.rpx),

        //         buildSort(),
        //         SizedBox(height: 5.rpx),
        //          buildListContainer(),
        //         inReview()
        //             ? Container(height: max(10, kSafeBottom))
        //             : SizedBox(height: 54.rpx + max(10, kSafeBottom)),
        //       ],
        //     ),
        //     buildTop(),
        //     inReview() ? Container() : buildBottom(),
        //   ],
        // )
,
         buildTop(),
          inReview() ? Container() : buildBottom(),
        ]
        
        )
        );
  }

  buildTop() {
    return QGNavigationBar(
      title:"",
      titleStyle: const TextStyle(
        color: Colors.white,
      ),
      leftItem: GestureDetector(
        onTap: () {
          Navigator.of(context).pop();
        },
        child: Container(
          padding: EdgeInsets.all(15.rpx),
          child: QGImage(asset: "nav_back_white",width: 20.rpx),
        ),
      ),
    );
  }

  buildHeader() {
    if (headData is! Map) {
      return AspectRatio(aspectRatio: 16 / 9, child: Container());
    }

    return Stack(
      children: [
        
        AspectRatio(
          aspectRatio: 16 / 20,
          child: QGImage(asset: 'xiadanbg',width: 375.rpx),
        ),


          Positioned(
            top: 90.rpx,
            right: 60,
            left: 60,
            child:ClipRRect(
            borderRadius: BorderRadius.circular(10.rpx),
            child: AspectRatio(
              aspectRatio:1,
              child:ImageFiltered(
                 imageFilter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
                child: QGImage(url: headData["thumb_img"]),
              ),
            ),
          )
          ),

            Positioned(
              left: 0,
              right:0,
              bottom: 20,
              top: 0,
              child:Align(
                alignment: Alignment.center,
                child: QGImage(url: headData["thumb_img"],width: 220.rpx,height: 220.rpx),
              )
               ,
            ),

        // AspectRatio(
        //   aspectRatio: 16 / 9,
        //   child: QGImage(url: headData["thumb_img"]),
        // ),//xiadanbg
     
        Positioned(top: -10.rpx, right: 10.rpx, child: buildNotice()),
         inReview()
             ? Container()
            : Positioned(top: 30.rpx, right: 10.rpx, child: buildRecord()),

        Positioned(
            left: 0,
            right: 0,
            bottom: 10.rpx,
            child: Column(
              children: [
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // ClipRRect(
                    //   borderRadius: BorderRadius.circular(22.rpx),
                    //   child: QGImage(
                    //     url: headData["author_avatar"],
                    //     width: 44.rpx,
                    //     height: 44.rpx,
                    //   ),
                    // ),
                    // SizedBox(height: 5.rpx),
                    Text(
                      headData["name"] ?? "",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 18.rpx,
                          fontWeight: FontWeight.normal),
                    ),
                  ],
                ),
                SizedBox(height: 10.rpx),

                   Column(
          children: [
            Row( mainAxisAlignment: MainAxisAlignment.center,
              children: [
              Column(
                children: [
                   Text(
                   "限量",
                    style: TextStyle(
                        color: Color(0xffffffff),
                        fontSize: 13.rpx,
                       ),
                  ),
                   Text(
                   headData["total"] ?? "",
                    style: TextStyle(
                        color: Color(0xffffffff),
                        fontSize: 24.rpx,
                        fontWeight: FontWeight.bold
                       ),
                  ),
                ],
              ),
              SizedBox(width: 30.rpx,),
              Container(
                height: 30.rpx,
                decoration: BoxDecoration(
                  border: Border(
                    left: BorderSide(
                      color: Color(0XFF484848)
                    )
                  )
                ),
              ),
              SizedBox(width: 30.rpx,),

              Column(
                children: [
                   Text(
                   "流通",
                    style: TextStyle(
                        color: Color(0xffffffff),
                        fontSize: 13.rpx,
                       ),
                  ),
                   Text(
                  headData["circulation_amount"]??'',
                    style: TextStyle(
                        color: Color(0xffffffff),
                        fontSize: 24.rpx,
                        fontWeight: FontWeight.bold
                       ),
                  ),
                ],
              )
            ],),
          ],
        )
        

                // Row(
                //   mainAxisAlignment: MainAxisAlignment.center,
                //   children: [
                //     QGLimitWidget(num: headData["total"] ?? "",dnum:headData["circulation_amount"]),
                //     // SizedBox(width: 10.rpx),
                //     // headData?["mysterybox"] is List
                //     //     ? Container()
                //     //     : QGLimitWidget(
                //     //         num: "${headData?["circulation_amount"]}", type: 2),
                //   ],
                // ),
              ],
            )),
      ],
    );
  }

  buildNotice() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(height: 40.rpx),
        GestureDetector(
          onTap: toNotice,
          child: Container(
            alignment: Alignment.center,
            height: 30.rpx,
            padding: EdgeInsets.only(left: 10.rpx),
            // decoration: BoxDecoration(
            //   borderRadius: BorderRadius.only(
            //       topLeft: Radius.circular(15.rpx),
            //       bottomLeft: Radius.circular(15.rpx)),
            //   color: const Color.fromRGBO(0, 0, 0, 0.4),
            // ),
            child: Text(
              '相关公告',
              style: TextStyle(
                  color: const Color(0xffffffff),
                  fontSize: 12.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        ),
      ],
    );
  }

  buildRecord() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(height: 40.rpx),
        GestureDetector(
          onTap: toRecord,
          child: Container(
            alignment: Alignment.center,
            height: 30.rpx,
            padding: EdgeInsets.only(left: 10.rpx),
            // decoration: BoxDecoration(
            //   borderRadius: BorderRadius.only(
            //       topLeft: Radius.circular(15.rpx),
            //       bottomLeft: Radius.circular(15.rpx)),
            //   color: const Color.fromRGBO(0, 0, 0, 0.4),
            // ),
            child: Text(
              '买卖详情',
              style: TextStyle(
                  color: const Color(0xffffffff),
                  fontSize: 12.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        ),
      ],
    );
  }

  buildSort() {
   return
  Container(
    margin: EdgeInsets.symmetric(horizontal: 15.rpx),
    height: 50.rpx,
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(50.rpx),
      color: Color(0XFF0C1012)
    ),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(width: 2.rpx,),
        Expanded(child: 
        GestureDetector(
          onTap: (){
              ttype=0;
              onSwitch(0);
              setState(() {
                
              });
          },
          child: Container(
          height: 46.rpx,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Color(ttype==0? 0XFFFFFFFF :0XFF0C1012),
              borderRadius: BorderRadius.circular(50.rpx)
            ),
            child:Text('当前寄售',style: TextStyle(fontSize: 16,color: Color(ttype==0? 0XFF0C1012 :0XFFFFFFFF))),
          ),
        )
        
        )
          ,
           Expanded(child: 
             GestureDetector(
          onTap: (){
             ttype=1;
              onSwitch(1);

              setState(() {
                
              });
          },
          child: Container(
          height: 46.rpx,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Color(ttype==1? 0XFFFFFFFF :0XFF0C1012),
              borderRadius: BorderRadius.circular(50.rpx)
            ),
            child:Text('当前委托',style: TextStyle(fontSize: 16,color: Color(ttype==1? 0XFF0C1012 :0XFFFFFFFF))),
          ),
        )
           )
         ,
         Expanded(child: 
         GestureDetector(
          onTap: (){
             ttype=2;
              onSwitch(2);

              setState(() {
                
              });
          },
          child: Container(
          height: 46.rpx,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                            color: Color(ttype==2? 0XFFFFFFFF :0XFF0C1012),

              borderRadius: BorderRadius.circular(50.rpx)
            ),
            child:Text('当前求购',style: TextStyle(fontSize: 16,color: Color(ttype==2? 0XFF0C1012 :0XFFFFFFFF))),
          ),
        )
         )
          ,
        SizedBox(width: 2.rpx,),

    ],),
   );

    // return Row(
    //   children: [
    //     QGSortWidget(
    //         hideSortIndex: 2,
    //         current: type,
    //         items: inReview() ? ["按价格排序", "按编号排序"] : ["按价格排序", "按编号排序", "当前求购"],
    //         onSwitch: onSwitch),
    //   ],
    // );
  }

  Widget _buildItem(context, index) {
  
    if (list is List && list.length > index) {
      return mitemBuilder(context, index, list[index]);
    }
    return Container();
  }

  buildListContainer() {
 
    Expanded(
      child: 
       Container(
          margin: EdgeInsets.all(10.rpx),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6.rpx),
              color: const Color(0xFFFFFFFF)),
          child: Column(
            children: [
               buildList()
              ],
          )),
    );
  }

  buildBottom() {
    return
    Positioned(
        bottom: 0,
        child: Container(
          color: const Color(0XFF232A32),
          padding: EdgeInsets.only(
            top: 10,
              left: 0.rpx,
              right: 0.rpx,
              bottom: max(10, kSafeBottom)),
          width: kScreenWidth,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              isPurchase && ttype ==2
                  ?Expanded(child: Container(
                               margin: EdgeInsets.only(left: 15.rpx),

                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(50.rpx),
                  color: Color(0XFF111111)
                ),
                child: Row(
                  children: [
                    Expanded(
                  child: QGButton(title: "求购", enable: true, onTap: onPurchase)),
                  ],
                ),
              ))
                  
                  // Expanded(
                  //     child: QGOutlineButton(
                  //         title: "求购", enable: true, onTap: onPurchase))
                  : Container(),
                  isPurchase && ttype ==1
                  ?Expanded(child: Container(
               margin: EdgeInsets.only(left: 15.rpx),

                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(50.rpx),
                  color: Color(0XFF111111)
                ),
                child: Row(
                  children: [
                    Expanded(
                  child: QGButton(title: "委托", enable: true, onTap: onPurchase)),
                  ],
                ),
              ))
                  : Container(),

              SizedBox(width: (isPurchase ? 15 : 0).rpx),

              if(ttype==0)
              Expanded(child: 
              Container(
                // margin: EdgeInsets.symmetric(horizontal: 15.rpx),
                margin: EdgeInsets.only(right: 15.rpx),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(50.rpx),
                  color: Color(0XFF111111)
                ),
                child: Row(
                  children: [
                  isBatch
                  ? Expanded(
                      child:GestureDetector(
                      onTap: () {
                          onBatch();
                      },
                      child: Container(
                        alignment: Alignment.center,
                        height: 44.rpx,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(50.rpx),
                          ),
                        child: Text(
                          '批量下单', 
                          style: TextStyle(
                              color:Color(0XFFFFFFFF),
                              fontSize: 14.rpx,
                              fontWeight: FontWeight.normal),
                        ),
                      ),
                    ))
                          // QGButton(title: "批量下单", enable: true, onTap: onBatch))
                  : Container(),
                    SizedBox(width: (isBatch ? 15 : 0).rpx),
                    Expanded(
                     child: QGButton(title: "快捷下单", enable: true, onTap: onFast)
                    ),
                  ],
                ),
              )
              )
              

             
            ],
          ),
        ));
  }

  onSwitch(index) {
    type = index;
    list = null;
    if (index == 2) {
      listURL = url_ask_orderList;
      listKey = "list";
    } else {
      if(index == 1){
        listURL = url_entrust_orderList;
      listKey = "list";
      }else{
 listURL = url_market_collectionList;
      listKey = "data";
      }
     
    }

    setState(() {});
    onRefresh();
  }

  mitemBuilder(context, index, data) {
    if (type == 2) {
      data["thumb_img"] = headData?["thumb_img"];
      data["total"] = headData?["total"];
      return QGSaleRecordCell(data: data ?? {});
    }

    if (inReview()) {
      data?["price"] = "888";
    }

    return GestureDetector(
        onTap: () {
   
          print(22222);
          print(inReview());

          if (data["isOwner"] == 1) {
            toast("不能购买自己流转的藏品");
            return;
          }

          Navigator.of(context).pushNamed(
              inReview() ? PageReviewTradeDetail : PageTradeNFTDetail,
              arguments: data["cid"]);
        },
        child: QGSaleDetailCell(data: data ?? {})
         );
  }

  @override
  itemBuilder(context, index, data) {
    if (type == 2) {
      data["thumb_img"] = headData?["thumb_img"];
      data["total"] = headData?["total"];
      return QGSaleRecordCell(data: data ?? {});
    }

    if (inReview()) {
      data?["price"] = "888";
    }

    return GestureDetector(
        onTap: () {
          print(111111);
          print(inReview());
          if (data["isOwner"] == 1) {
            toast("不能购买自己流转的藏品");
            return;
          }

          Navigator.of(context).pushNamed(
              inReview() ? PageReviewTradeDetail : PageTradeNFTDetail,
              arguments: data["cid"]);
        },
        child: QGSaleDetailCell(data: data ?? {})
         );
  }

  toNotice() {
    Navigator.of(context)
        .pushNamed(PageNoticeAboutGoods, arguments: headData["pid"]);
  }

  toRecord() {
    Navigator.of(context).pushNamed(PageTradeBuyList, arguments: headData);
  }

  checkHF() async {
    if (isWallet) return true;

    var res = await Network.post(url_u_getMergedUserInfo, context: context);
    if (!res.success) {
      toast(res.msg);
      return;
    }

    if (res.data["huifu_wallet"] != 1) {
      QGOpenWalletWidget.show(context, () async {
        Navigator.of(context)
            .pushReplacementNamed(PageSelectWallet)
            .then((value) {
          onRefresh();
        });
      });
      return false;
    }
    return true;
  }

  onPurchase() async {
    //是否已开通钱包
    if (!await checkHF()) {
      return;
    }


    showModalBottomSheet(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20.rpx)),
                      context: context,
                      backgroundColor: Color(0xFF232A32),
                      builder: (BuildContext context) {
                        return SingleChildScrollView(
                          child: Container(
                              padding: EdgeInsets.only(
                                  bottom:
                                      MediaQuery.of(context).viewInsets.bottom),
                              child:
                                  QGSendCodeDialog1(url: url_u_cancelAccount,data:headData,ttype:ttype)),
                        );
                      });

   // Navigator.of(context).pushNamed(PageInitiatePurchase, arguments: headData);
  }

  onFast() async {
    //是否已开通钱包
    if (!await checkHF()) {
      return;
    }

    showLoading(context);

    var param = {"pid": widget.id, "pay_type": "HUIFU"};
    Network.post(url_market_repidPayOrder, data: param).then((res) {
      if (!res.success) {
        dismissLoading();
        toast(res.msg);
        return;
      }

      var rawData = res.data;
      var cid = rawData["cid"];
      var param = {"cid": cid};
      Network.post(url_market_collectionInfo, data: param).then((res) {
        if (!res.success) {
          dismissLoading();
          toast(res.msg);
          return;
        }

        dismissLoading();
        res.data["order_price"] = res.data["price_consignment"];
        Navigator.of(context)
            .pushNamed(PageTradeOrderConfirm, arguments: res.data)
            .then((value) {});
      });
    });
  }

  onBatch() async {
    //是否已开通钱包
    if (!await checkHF()) {
      return;
    }
    onConfirm(price, count, payType) {
      var param = {};
      param["pid"] = widget.id;
      param["pay_type"] = "HUIFU";
      param["limitPrice"] = price;
      param["orderCount"] = count;

      onResponse(res) {
        if (!res.success) {
          toast(res.msg);
          return;
        }

        var url = res.data["pay_url"];
        if (url is String) {
          Navigator.of(context).pushNamed(PageQGPayWebView, arguments: url);
        }
      }

      var url = url_market_batchBuy;
      Map<String, dynamic> stringMap = param.cast<String, dynamic>();

      Network.post(url, data: stringMap, context: context).then(onResponse);
    }

    QGBatchAlert.show(context, onConfirm: onConfirm);
  }
}
